

package com.ltu.payment.util;

import java.io.BufferedReader;
import java.io.ByteArrayInputStream;
import java.io.IOException;
import java.io.InputStreamReader;
import java.io.UnsupportedEncodingException;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Collections;
import java.util.HashMap;
import java.util.Iterator;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.SortedMap;
import java.util.TreeMap;

import javax.servlet.ServletInputStream;
import javax.servlet.http.HttpServletRequest;

import org.apache.commons.codec.digest.DigestUtils;
import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import org.xml.sax.InputSource;

import net.sf.json.JSONObject;

/**
 * 
 * XML的工具方法   
 */
@SuppressWarnings({"rawtypes","unchecked"})
public class XmlUtils {
    
    /** 
     * request转字符串
     * @param request
     * @return
     */
    public static String parseRequst(HttpServletRequest request){
        String body = "";
        try {
            ServletInputStream inputStream = request.getInputStream(); 
            BufferedReader br = new BufferedReader(new InputStreamReader(inputStream));
            while(true){
                String info = br.readLine();
                if(info == null){
                    break;
                }
                if(body == null || "".equals(body)){
                    body = info;
                }else{
                    body += info;
                }
            }
        } catch (UnsupportedEncodingException e) {
            e.printStackTrace();
        } catch (IOException e) {
            e.printStackTrace();
        }            
        return body;
    }
    
    public static String parseXML(SortedMap<String, String> parameters) {
        StringBuffer sb = new StringBuffer();
        sb.append("<xml>");
        Set es = parameters.entrySet();
        Iterator it = es.iterator();
        while (it.hasNext()) {
            Map.Entry entry = (Map.Entry)it.next();
            String k = (String)entry.getKey();
            String v = (String)entry.getValue();
            if (null != v && !"".equals(v) && !"appkey".equals(k)) {
                sb.append("<" + k + ">" + parameters.get(k) + "</" + k + ">\n");
            }
        }
        sb.append("</xml>");
        return sb.toString();
    }

    /**
     * 从request中获得参数Map，并返回可读的Map
     * 
     * @param request
     * @return
     */
    public static SortedMap getParameterMap(HttpServletRequest request) {
        // 参数Map
        Map properties = request.getParameterMap();
        // 返回值Map
        SortedMap returnMap = new TreeMap();
        Iterator entries = properties.entrySet().iterator();
        Map.Entry entry;
        String name = "";
        String value = "";
        while (entries.hasNext()) {
            entry = (Map.Entry) entries.next();
            name = (String) entry.getKey();
            Object valueObj = entry.getValue();
            if(null == valueObj){
                value = "";
            }else if(valueObj instanceof String[]){
                String[] values = (String[])valueObj;
                for(int i=0;i<values.length;i++){
                    value = values[i] + ",";
                }
                value = value.substring(0, value.length()-1);
            }else{
                value = valueObj.toString();
            }
            returnMap.put(name, value.trim());
        }
        returnMap.remove("method");
        return returnMap;
    }
    
    /**
     * 转XMLmap
     * @author  
     * @param xmlBytes
     * @param charset
     * @return
     * @throws DocumentException 
     * @throws Exception
     */
    public static Map<String, String> toMap(byte[] xmlBytes,String charset) throws DocumentException {
        SAXReader reader = new SAXReader(false);
        InputSource source = new InputSource(new ByteArrayInputStream(xmlBytes));
        source.setEncoding(charset);
        Document doc = reader.read(source);
        Map<String, String> params = XmlUtils.toMap(doc.getRootElement());
        return params;
    }
    
    /**
     * 转MAP
     * @author  
     * @param element
     * @return
     */
    public static Map<String, String> toMap(Element element){
        Map<String, String> rest = new HashMap<String, String>();
        List<Element> els = element.elements();
        for(Element el : els){
            rest.put(el.getName().toLowerCase(), el.getTextTrim());
        }
        return rest;
    }
    
    public static String toXml(Map<String, String> params){
        StringBuilder buf = new StringBuilder();
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        buf.append("<xml>");
        for(String key : keys){
            buf.append("<").append(key).append(">");
            buf.append("<![CDATA[").append(params.get(key)).append("]]>");
            buf.append("</").append(key).append(">\n");
        }
        buf.append("</xml>");
        return buf.toString();
    }
    public static String toXml2(Map<String, Object> params){
        StringBuilder buf = new StringBuilder();
        List<String> keys = new ArrayList<String>(params.keySet());
        Collections.sort(keys);
        buf.append("<xml>");
        for(String key : keys){
            buf.append("<").append(key).append(">");
            buf.append("<![CDATA[").append(params.get(key)).append("]]>");
            buf.append("</").append(key).append(">\n");
        }
        buf.append("</xml>");
        return buf.toString();
    }
    
	/**
	 * 
	 * @date 2018年12月28日
	 * @author 若尘
	 * @Description 微信小程序支付签名并且转换成XML字符
	 * @param json
	 * @param payKey
	 * @return 返回xml字符
	 * String
	 */
	public static  String  paramSort(Map<String,Object> json,String payKey){
		StringBuilder result=new StringBuilder();
		String key = "&key="+payKey;
		String[] arr = new String[json.keySet().size()];
		json.keySet().toArray(arr);
		int len = arr.length;
		Arrays.sort(arr);//QueryString排序
		for (int i = 0; i < len; i++) {
			result.append(arr[i]); 
			result.append("="); 			
			result.append(json.get(arr[i])); 
			if (i < len - 1) 
				result.append("&"); 
		}
		System.out.println("\n 排好序的字符串" + result);
		result.append(key);  
		System.out.println("\n 等待加密的字符串：" + result);
		String sign = DigestUtils.md5Hex(result.toString()).toUpperCase();
		
		System.out.println("\n Md5加密后且转为大写的签名字符串：" + sign);
		json.put("sign", sign);
		String xmlStr=	XmlUtils.toXml2(json);
		System.out.println("\n 参数转XML字符串：" + xmlStr);
		return xmlStr;
	}

	public static boolean verifySign2(Map<String, String> json, String payKey, String verifySign) {
		StringBuilder result = new StringBuilder();
		String key = "&key=" + payKey;
		String[] arr = new String[json.keySet().size()];
		json.keySet().toArray(arr);
		int len = arr.length;
		Arrays.sort(arr);// QueryString排序
		for (int i = 0; i < len; i++) {
			result.append(arr[i]);
			result.append("=");
			result.append(json.get(arr[i]));
			if (i < len - 1) {
				result.append("&");
			}
		}
		System.out.println("\n 排好序的字符串" + result);
		result.append(key);
		System.out.println("\n 等待加密的字符串：" + result);
		String sign = DigestUtils.md5Hex(result.toString()).toUpperCase();
		System.out.println("\n Md5加密后且转为大写的签名字符串：" + sign);
		return verifySign.equals(sign);
		
	}
	
	
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
    
	
    
}

